package me.zhengjie.modules.biz.utils;

import cn.hutool.bloomfilter.bitMap.BitMap;
import com.alipay.api.internal.util.file.IOUtils;
import me.zhengjie.config.AppConfig;
import org.apache.commons.imaging.ImageFormats;
import org.apache.commons.imaging.Imaging;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.AbstractBarcodeBean;
import org.krysalis.barcode4j.impl.codabar.CodabarBean;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.impl.code39.Code39Bean;
import org.krysalis.barcode4j.impl.datamatrix.DataMatrixBean;
import org.krysalis.barcode4j.impl.fourstate.RoyalMailCBCBean;
import org.krysalis.barcode4j.impl.fourstate.USPSIntelligentMailBean;
import org.krysalis.barcode4j.impl.int2of5.Interleaved2Of5Bean;
import org.krysalis.barcode4j.impl.pdf417.PDF417Bean;
import org.krysalis.barcode4j.impl.postnet.POSTNETBean;
import org.krysalis.barcode4j.impl.upcean.EAN13Bean;
import org.krysalis.barcode4j.impl.upcean.EAN8Bean;
import org.krysalis.barcode4j.impl.upcean.UPCABean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @version 1.0.0
 * @description: 条形码工具类
 * @date 2022/11/24 11:15
 */
public class BarcodeUtil {
/*                <dependency>
                <groupId>net.sf.barcode4j</groupId>
                <artifactId>barcode4j-light</artifactId>
                  <version>2.0</version>
                      </dependency>*/

    /**
     * 生成code39条形码
     *
     * @param message       要生成的文本
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
//    public static String path = "/tmp/xxx.png";

    public static String path = "C:\\Users\\Dell\\Desktop\\xxx.png";
    public static byte[] generateBarCode39(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone,String path) {

        return generateBar(new Code39Bean(), message, fontSize, height, width, withQuietZone, quietZone ,path);
    }

    /**
     * 生成code128条形码
     *
     * @param message       要生成的文本
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarCode128(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone, String path) {

        return generateBar(new Code128Bean(), message, fontSize, height, width, withQuietZone, quietZone,path);
    }

    public static void printBarCode128(String msg,String path){
         printBar(msg,path);
    }

    private static void printBar(String msg,String path) {

        try {
            File file=new File(path);
            OutputStream ous=new FileOutputStream(file);
            //选择条形码类型(好多类型可供选择)
            Code128Bean bean=new Code128Bean();
            //设置长宽
            final double moduleWidth=0.20;
            final int resolution=300;
            bean.setModuleWidth(moduleWidth);
            bean.doQuietZone(false);
            bean.setFontName(null);
            bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);
            String format = "image/png";
            // 输出流
            BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format,
                    resolution, BufferedImage.TYPE_BYTE_BINARY, false, 0);
            //生成条码
            bean.generateBarcode(canvas,msg);
            canvas.finish();
            ous.close();
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成EAN13条形码
     *
     * @param message       要生成的文本  Valid are 0-9 only length: 11-12
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarEAN13(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone,String path) {

        return generateBar(new EAN13Bean(), message, fontSize, height, width, withQuietZone, quietZone,path);
    }

    /**
     * 生成EAN8条形码
     *
     * @param message       要生成的文本 Valid are 0-9 only length: 7-8
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarEAN8(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone,String path) {

        return generateBar(new EAN8Bean(), message, fontSize, height, width, withQuietZone, quietZone,path);
    }

    /**
     * 生成Codabar条形码
     *
     * @param message       要生成的文本 Valid are 0-9 and a-e
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarCodabar(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone,String path) {

        return generateBar(new CodabarBean(), message, fontSize, height, width, withQuietZone, quietZone,path);
    }

    /**
     * 生成UPCA条形码
     *
     * @param message       要生成的文本 Valid are 0-9 lenth:11-12
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarUPCA(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone,String path) {

        return generateBar(new UPCABean(), message, fontSize, height, width, withQuietZone, quietZone,path);
    }

    /**
     * 生成POSTNET条形码
     *
     * @param message       要生成的文本 Valid are 0-9
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarPOSTNET(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone,String path) {

        return generateBar(new POSTNETBean(), message, fontSize, height, width, withQuietZone, quietZone,path);
    }

    /**
     * 生成RoyalMailCBC条形码
     *
     * @param message       要生成的文本 Valid are 0-9
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarRoyalMailCBC(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone,String path) {

        return generateBar(new RoyalMailCBCBean(), message, fontSize, height, width, withQuietZone, quietZone,path);
    }

    /**
     * 生成USPSIntelligentMail条形码
     *
     * @param message       要生成的文本 Valid are 0-9 length:20
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarUSPSIntelligentMail(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone,String path) {

        return generateBar(new USPSIntelligentMailBean(), message, fontSize, height, width, withQuietZone, quietZone,path);
    }

    /**
     * 生成PDF417条形码
     *
     * @param message       要生成的文本 Valid are 0-9 length:20
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarPDF417(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone,String path) {

        return generateBar(new PDF417Bean(), message, fontSize, height, width, withQuietZone, quietZone,path);
    }

    /**
     * 生成DataMatrix条形码
     *
     * @param message       要生成的文本 Valid are 0-9 length:20
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarDataMatrix(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone,String path) {

        return generateBar(new DataMatrixBean(), message, fontSize, height, width, withQuietZone, quietZone,path);
    }

    /**
     * 生成Interleaved2Of5条形码
     *
     * @param message       要生成的文本 Valid are 0-9
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarInterleaved2Of5(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone,String path) {

        return generateBar(new Interleaved2Of5Bean(), message, fontSize, height, width, withQuietZone, quietZone,path);
    }

    /**
     * 生成条形码
     *
     * @param bean          条形码类型
     * @param message       要生成的文本
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    private static byte[] generateBar(AbstractBarcodeBean bean, String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone,String path) {

        // 条码数据显示位置
        bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);

        if (fontSize != null) {
            bean.setFontSize(fontSize);
        } else {
            bean.setFontSize(5);
        }
        // 两端留白宽度
        if (quietZone != null) {
            bean.setQuietZone(quietZone);
        }

        // 精细度
        final int dpi = 256;

        // 设置条码每一条的宽度
        // UnitConv 是barcode4j 提供的单位转换的实体类，用于毫米mm,像素px,英寸in,点pt之间的转换
        // 设置条形码高度和宽度
        if (height != null) {
            bean.setBarHeight(height);
        } else {
            bean.setBarHeight(20);
        }
        if (width != null) {
            bean.setModuleWidth(UnitConv.in2mm(width / dpi));
        } else {
            bean.setModuleWidth(UnitConv.in2mm(5.0f / dpi));
        }

        // 设置两侧是否留白
        bean.doQuietZone(withQuietZone);

        if(path!=null){

        }else {

        }
        String format = "image/png";
        ByteArrayOutputStream ous = null;
        byte[] imageByte;
        try {
            ous = new ByteArrayOutputStream();
            // 输出到流
            BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi,
                    BufferedImage.TYPE_BYTE_BINARY, false, 0);
            // 生成条形码
            bean.generateBarcode(canvas, message);
            // 结束绘制
            canvas.finish();
            imageByte = ous.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (null != ous) {
                    ous.close();
                }
            } catch (Exception e) {

            }
        }
        return imageByte;
    }

    public static String barBase64(String msg){
        byte[] bytes = generateBarCode128(msg, null, null, null, true, null,null);
        // byte[]转base64
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static void  downloadPicture(String name, HttpServletResponse response){
        try {
            File file = new File(path);
            long size = file.length() / 1024;

            FileInputStream fileInputStream = new FileInputStream(new File(path));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/png");
            response.setHeader("Content-Description","File Transfer");
//            response.setCharacterEncoding("UTF-8");
//            response.setContentType("text/html;charset=UTF-8");
            name = name+".png";
            String fileName = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            response.setHeader("Content-Disposition","attachment; filename="+fileName);
            response.setHeader("Content-Length",file.length()+"");
            response.setHeader("Content-Type","application/octet-stream");
            response.setHeader("Expires","0");
            response.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Content-Transfer-Encoding","binary");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addText(String ChineseName,String path){
        BufferedImage src= null;
        try {
            src = ImageIO.read(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(src.getWidth());
        System.out.println(src.getHeight());
        BufferedImage b=new BufferedImage(src.getWidth()+10,src.getHeight()+75,src.getType());
        Graphics2D g2d=b.createGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0,0,b.getWidth(),b.getHeight());
        g2d.drawImage(src,55,55,null);
        g2d.dispose();
        try {
            ImageIO.write(b,"png", new File(path));//写出文件
        } catch (IOException e) {
            e.printStackTrace();
        }

        BufferedImage image = null;
        try {
            image = ImageIO.read(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }

        Graphics2D pen = image.createGraphics();
        // 设置画笔颜色为白色
        // pen.setColor(Color.WHITE);
        pen.setColor(new Color(0, 0, 0, 255));
        // 设置画笔字体样式为微软雅黑，斜体，文字大小为20px
        Font font = new Font("宋体", Font.PLAIN, 20);
        pen.setFont(font);
        BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        FontMetrics fm = img.getGraphics().getFontMetrics(font);
        int width = fm.stringWidth(ChineseName);
        // 写上水印文字和坐标
        pen.drawString(ChineseName, (image.getWidth()-width)/2, image.getHeight()-50);
        // 创建新图片文件
        File file = new File(path);
        // 将处理好的图片数据写入到新图片文件中
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            ImageIO.write(image, "png", fos);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        b=new BufferedImage(400,320,src.getType());
//        g2d=b.createGraphics();
//        g2d.drawImage(src,0,0,400,320,null);
//        g2d.dispose();
//        g2d.setComposite(AlphaComposite.Src);
//        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
//        g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
//        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
//        try {
//            ImageIO.write(b,"png", new File(path));//写出文件
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

    }
    public static void printBarCode(String msg,String name,String ChineseName ,HttpServletResponse response){
        printBarCode128(msg,path);
        addText(ChineseName,path);
        downloadPicture(name,response);
    }
    public static void bulkPrintBarCode(String msg,String name,String ChineseName,String path){
        printBarCode128(msg,path);
        addText(ChineseName,path);
//        downloadPicture(name,response);
    }
    static Object obj = new Object();
    public static void showBarCode(String msg, String name, Integer serialNumber, String ChineseName, HttpServletResponse response) {
        String path = AppConfig.baseBarCodePath +String.valueOf(serialNumber)+".png";

        System.out.println("path:" + path);
        synchronized(obj) {
            // 临界区
            showBarCode128(msg,path);
            addTextShow(ChineseName,path);
            showPicture(name,path,response);
        }

    }
    //等比放大图片
    private static void scaleImage(String path, double scale) throws Exception{
        BufferedImage bufferedImage = ImageIO.read(new File(path));
        int newWidth = (int) (bufferedImage.getWidth() * scale);//新宽度
        int newHeight = (int) (bufferedImage.getHeight() * scale);//新高度
        BufferedImage image = new BufferedImage(newWidth, newHeight, bufferedImage.getType());
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(bufferedImage, 0, 0, newWidth, newHeight, null);
        g.dispose();
        ImageIO.write(image, "png", new File(path));
    }
    //向png图片文件中写入DPI信息
    private static void writeDPIToPng(String path, int dpi)throws Exception{
        File imageFile = new File(path);
        BufferedImage image = ImageIO.read(imageFile);

        // 计算图像的宽度和高度，根据 DPI
        int widthInPixels = (int) (image.getWidth() * 72.0 / dpi);  // 72 是默认的 DPI
        int heightInPixels = (int) (image.getHeight() * 72.0 / dpi);

        // 创建一个新的 BufferedImage 来设置 DPI
        BufferedImage newImage = new BufferedImage(widthInPixels, heightInPixels, BufferedImage.TYPE_INT_ARGB);

        // 使用 Graphics2D 来绘制原图像到新的 BufferedImage 中
        Graphics2D g2d = newImage.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();

        // 设置输出文件
        File output = new File(imageFile.getParent(), "null.png");

        // 创建参数 Map 来设置 DPI 信息
        Map<String, Object> params = new HashMap<>();
        params.put("dpi", dpi);  // 在这个参数中指定 DPI 信息

        // 保存图像，设置 DPI
        ImageIO.write(newImage, "PNG", output);
    }
    private static void showBarCode128(String msg,String path) {
        try {
            File file=new File(path);
            OutputStream ous=new FileOutputStream(file);
            //选择条形码类型(好多类型可供选择)
            Code128Bean bean=new Code128Bean();
            //设置长宽
            final double moduleWidth=0.30;
            final int resolution=300;//分辨率DPI
            bean.setModuleWidth(moduleWidth);
            bean.setHeight(25.0);//设置条形码高度默认为20.0mm
            bean.doQuietZone(false);
            bean.setFontName(null);
            bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);
            String format = "image/png";
            // 输出流
            BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format,
                    resolution, BufferedImage.TYPE_BYTE_BINARY, false, 0);
            //生成条码
            bean.generateBarcode(canvas,msg);
            canvas.finish();
            scaleImage(path,1.5);
            //writeDPIToPng(path, 300);
        }catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static void addTextShow(String ChineseName,String path){
        System.out.println("--------------------------");
        System.out.println("path: " + path);
        BufferedImage src= null;
        try {
            src = ImageIO.read(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("width: " + src.getWidth());
        System.out.println("height: " + src.getHeight());
        BufferedImage b=new BufferedImage(src.getWidth()+20,src.getHeight()+75,src.getType());
        Graphics2D g2d=b.createGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0,0,b.getWidth(),b.getHeight());
        g2d.drawImage(src,10,25,null);
        g2d.dispose();
        try {
            ImageIO.write(b,"png", new File(path));//写出文件
        } catch (IOException e) {
            e.printStackTrace();
        }

        BufferedImage image = null;
        try {
            image = ImageIO.read(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("width**: " + image.getWidth());
        System.out.println("height**: " + image.getHeight());
        Graphics2D pen = image.createGraphics();
        // 设置画笔颜色为白色
        // pen.setColor(Color.WHITE);
        pen.setColor(new Color(0, 0, 0, 255));
        // 设置画笔字体样式为微软雅黑，斜体，文字大小为20px
        Font font = new Font("黑体", Font.PLAIN, 30);
        pen.setFont(font);
        BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        FontMetrics fm = img.getGraphics().getFontMetrics(font);
        int width = fm.stringWidth(ChineseName);
        // 写上水印文字和坐标
        pen.drawString(ChineseName, (image.getWidth()-width)/2, image.getHeight()-20);
        // 创建新图片文件
        File file = new File(path);
        // 将处理好的图片数据写入到新图片文件中
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            ImageIO.write(image, "png", fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void  showPicture(String name, String path, HttpServletResponse response){
        try {
            File file = new File(path);
            long size = file.length() / 1024;

            FileInputStream fileInputStream = new FileInputStream(new File(path));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/png");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 将存放在sourceFilePath目录下的源文件，打包成fileName名称的zip文件，并存放到zipFilePath路径下
     *
     * @param sourceFilePath:待压缩的文件路径
     * @param zipFilePath:压缩后存放路径
     * @param fileName:压缩后文件的名称
     * @return
     */
    public static boolean tozip(String sourceFilePath, String zipFilePath, String fileName) {
        boolean flag = false;
        File sourceFile = new File(sourceFilePath);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
// DeflaterOutputStream ：压缩类的基类。
// ZipOutputStream ：DeflaterOutputStream的一个子类，把数据压缩成Zip文件格式。// GZIPOutputStream ：DeflaterOutputStream的一个子类把数据压缩成GZip文件格式//
// InflaterInputStream ：解压缩类的基类
// ZipInputStream ：InflaterInputStream的一个子类，能解压缩Zip格式的数据
// GZIPInputStream ：InflaterInputStream的一个子类，能解压缩Zip格式的数据
        if (!sourceFile.exists()) {
            System.out.println(sourceFilePath + "没有需要压缩的文件");
        } else {
            try {
                File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
                if (zipFile.exists()) {
                    System.out.println(sourceFilePath + "已经存在" + fileName + ".zip");
                } else {
                    File[] sourceFiles = sourceFile.listFiles();
                    if (null == sourceFiles || sourceFiles.length < 1) {
                        System.out.println(sourceFilePath + "里面不存在文件，无需压缩.");
                    } else {
                        fos = new FileOutputStream(zipFile);
                        zos = new ZipOutputStream(new BufferedOutputStream(fos));
                        byte[] bufs = new byte[1024 * 10];
                        for (int i = 0; i < sourceFiles.length; i++) {
// 创建ZIP实体，并添加进压缩包
                            ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                            System.out.println(zipEntry);
// encoding
                            zos.putNextEntry(zipEntry);
// 读取待压缩的文件并写进压缩包里
                            fis = new FileInputStream(sourceFiles[i]);
                            bis = new BufferedInputStream(fis, 1024 * 10);
                            int read = 0;
                            while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                                zos.write(bufs, 0, read);
                            }
                            fis.close();
                            bis.close();
                        }
                        flag = true;
                        zos.close();
                        fos.close();

                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                try {
                    if (null != bis)
                        bis.close();
                    if (null != zos)
                        zos.close();
                    if (null != fos)
                        fos.close();
                    if (null != fis)
                        fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        return flag;
    }

    public static void downFile(String FilePath, String str,HttpServletResponse response) {
        Map m = new HashMap();
        try {

            String path = FilePath +"/"+ str;
            File file = new File(path);
            if (file.exists()) {
                InputStream ins = new FileInputStream(path);
                BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
                OutputStream outs = response.getOutputStream();// 获取文件输出IO流
                BufferedOutputStream bouts = new BufferedOutputStream(outs);
                response.addHeader("content-disposition", "attachment;filename="
                        + java.net.URLEncoder.encode(str, "UTF-8"));
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                // 开始向网络传输文件流
                while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
                    bouts.write(buffer, 0, bytesRead);
                }
                bouts.flush();// 这里一定要调用flush()方法
                ins.close();
                bins.close();
                outs.close();
                bouts.close();
            }
        } catch (IOException e) {
            m.put("code", "-1");
            m.put("text", "附件下载出错：" + e.getMessage());
            e.printStackTrace();
        }
    }
}

